package cn.itsource.pethome.user.controller;

import cn.itsource.pethome.basic.constant.PetHomeConstant;
import cn.itsource.pethome.basic.util.AjaxResult;
import cn.itsource.pethome.user.domain.dto.UserDto;
import cn.itsource.pethome.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService wechatService;

    //申请授权码
    @GetMapping("/toRequestCode")
    public String toRequestCode(){
        return "redirect:"+PetHomeConstant.CODEURL.replace("APPID", PetHomeConstant.APPID)
                .replace("REDIRECT_URI", PetHomeConstant.REDIRECT_URI);
    }

    @RequestMapping("/callback")
    public String callback(String code) {
        //跳转到门户网站callback.html页面
        return "redirect:http://localhost:8082/callback.html?code=" + code;
    }

    //处理回调请求
    @PostMapping("/handleCallBack")
    @ResponseBody
    public AjaxResult handleCallBack(@RequestBody Map<String,String> param){
        try {
            //获取授权码
            String code = param.get("code");
            //通过授权码获取token
            Map<String, Object> map = wechatService.handleCallBack(code);

            return new AjaxResult().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }
    }


    //绑定微信用户信息
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody UserDto userDto){
        try {
            //微信和用户绑定在一起
            Map<String, Object> map = wechatService.binder(userDto);
            return new AjaxResult().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, e.getMessage());
        }

    }

}
